package com.ele.client.editor;

import com.ele.client.Presenter;
import com.ele.client.rpc.ApplicationServiceAsync;
import com.ele.model.Answer;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ControlLabel;
import com.github.gwtbootstrap.client.ui.TextArea;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class AnswerPresenter implements Presenter {

    public interface Display {
        Widget asWidget();

        ControlLabel getLabel();

        TextArea getTextArea();

        Button getDeleteButton();
    }

    private final ApplicationServiceAsync rpcService;
    private final HandlerManager eventBus;
    private final Display display;
    private final QuestionPresenter parentPresenter;

    private Answer value;

    public AnswerPresenter(ApplicationServiceAsync rpcService, HandlerManager eventBus, Display display, QuestionPresenter parentPresenter) {
        this.rpcService = rpcService;
        this.eventBus = eventBus;
        this.display = display;
        this.parentPresenter = parentPresenter;

        bind();
    }

    public void go(final HasWidgets container) {
        bind();
        container.clear();
        container.add(display.asWidget());
    }

    private void bind() {
        display.getDeleteButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                parentPresenter.remove(AnswerPresenter.this);
            }
        });
    }

    public void setValue(Answer answer) {
        value = answer;

//        display.getLabel().setText("Answer #" + answer.getId());
        display.getTextArea().setValue(answer.getText());
    }

    public Answer getValue() {
        value.setText(display.getTextArea().getText());

        return value;
    }

    public Display getDisplay() {
        return display;
    }

    public void setFocus(boolean focused) {
        display.getTextArea().setFocus(focused);
    }
}
